<!-- CreateRoleDialog.vue -->
<template>
  <div class="total">
    <div class="content">
      <el-button @click="$router.back()" :icon="ArrowLeft" type="primary">
        返回
      </el-button>
      <h2 style="color: black; margin-bottom: 24px">创建角色</h2>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="92px">
        <el-form-item label="角色名" prop="name">
          <el-input v-model="form.name" placeholder="如：哈利波特" maxlength="30" show-word-limit />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
            <el-radio label="other">其他</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="角色性格" prop="desc">
          <el-input
            v-model="form.desc"
            type="textarea"
            :rows="3"
            placeholder="如：勇敢、乐观，喜欢用魔法帮助他人……"
            maxlength="120"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="角色照片" prop="img">
          <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            :show-file-list="false"
            accept="image/*"
            :on-change="handleAvatarChange"
          >
            <div v-if="!form.img" class="uploader-placeholder">
              <el-icon><Plus /></el-icon>
              <span>点击选择图片</span>
            </div>
            <el-image
              v-else
              :src="form.img"
              fit="cover"
              style="width: 120px; height: 120px; border-radius: 12px"
            />
          </el-upload>
          <div class="el-form-item__extra">建议使用方形图片，便于展示。</div>
        </el-form-item>
      </el-form>
      <div class="button">
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" :loading="saving" @click="onSave">确认</el-button>
      </div>

      <!-- 示例：展示已创建的 roles -->
      <div style="margin-top:16px" v-if="roles.length">
        <el-card v-for="(r, idx) in roles" :key="idx" style="margin-bottom:12px">
          <template #header><strong>{{ r.name }}</strong></template>
          <div style="display:flex; gap:12px; align-items:center">
            <el-image :src="r.img" style="width:72px; height:72px; border-radius:8px" fit="cover" />
            <div>
              <div>{{ r.desc }}</div>
              <div style="color:#909399; font-size:12px">已生成 prompt 函数</div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, ArrowLeft } from '@element-plus/icons-vue'
import { useRolesStore } from '@/stores/roles'

const router = useRouter()
const store = useRolesStore()
const roles = ref([])

const saving = ref(false)
const form = reactive({
  name: '',
  gender: 'male',
  desc: '',
  img: ''
})
const formRef = ref(null)
const rules = {
  name: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  desc: [{ required: true, message: '请输入角色性格/描述', trigger: 'blur' }],
  img: [{ required: true, message: '请上传角色照片', trigger: 'change' }]
}

function handleAvatarChange(file) {
  if (!file || !file.raw) return
  if (!file.raw.type.startsWith('image/')) return ElMessage.error('只能上传图片文件')
  if (file.raw.size / 1024 / 1024 >= 5) return ElMessage.error('图片大小需小于 5MB')
  form.img = URL.createObjectURL(file.raw)
}

function reset() {
  form.name = ''
  form.gender = 'male'
  form.desc = ''
  form.img = ''
}

function onSave() {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      saving.value = true
      const newRole = {
        name: form.name,
        desc: form.desc,
        img: form.img,
        prompt: (input) =>
          `你现在是假装自己是${form.name}，请用与其性格“${form.desc}”相符的口吻回答：“${input}”。内容应带有鼓励，并带入该角色的世界观特色。`
      }
      store.addRole(newRole)     // ✅ 加入到共享的 roles
      ElMessage.success('已创建角色')
      router.back()              // 返回父页面
    } finally {
      saving.value = false
    }
  })
}

</script>

<style scoped>
.total {
  min-width: 100vh;
  min-height: 100vh;
  margin: 0 auto;
  font-family: sans-serif;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  background-image: url('/bg_shouye.png');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
  background-attachment: fixed;
}

.content {
  padding: 24px;
  max-width: 480px;
  margin: auto;
}

.uploader-placeholder {
  width: 120px;
  height: 120px;
  border: 1px dashed var(--el-border-color);
  border-radius: 12px;
  display: grid;
  place-items: center;
  gap: 6px;
  color: var(--el-text-color-secondary);
  cursor: pointer;
}
</style>
